use base 'Catalyst::Controller::HTML::FormFu';

=head2 formfu_create

Use HTML::FormFu to create a new book

=cut

sub formfu_create :Local :FormConfig {
	my ($self, $c) = @_;

	# Get the form that the :FormConfig attribute saved in the stash
	my $form = $c->stash->{form};

	# Check if the form as been submitted (vs. displaying the initial
	# form) and if the data based validation.  "submitted_and_valid"
	# is shorthand for "$form->submitted && !$form->has_errors"
	if ($form->submitted_and_valid) {
		# Create a new book
		my $book = $c->model('DB::Books')->new_result({});
		# Save the form data for the book
		$form->save_to_model($book);
		# Set a status message for the user
		$c->flash->{status_msg} = 'Book created';
		# Return to the books list
		$c->response->redirect($c->uri_for('list')); 
		$c->detach;
	} else {
		# Get the authors from the DB
		my @authorObjs = $c->model("DB::Authors")->all();
		# Create an array of arrayrefs where each arrayref is an author
		my @authors;
		foreach (sort {$a->last_name cmp $b->last_name} @authorObjs) {
			push(@authors, [$_->id, $_->last_name]);
		}
		# Get the select added by the config file
		my $select = $form->get_element({type => 'Select'});
		# Add the authors to it
		$select->options(\@authors);
	}

	# Set the template
	$c->stash->{template} = 'books/formfu_create.tt2';
}